package appTempl

import (
	"eccgateway/pkg/api/dataselect"
	"eccgateway/pkg/db/util"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

type StarTempl struct {
	Uuid       string    `json:"id" orm:"column(id);unique;pk"`
	UserId     string    `json:"user_id" orm:"column(user_id)"`
	CreateTime time.Time `json:"createTime" orm:"column(createTime)"`
	Templ      *Templ    `json:"templ" orm:"rel(fk)"`
}

var existKeyInStarTempl = map[string]bool{
	"id":         true,
	"user_id":    true,
	"createTime": true,
}

func (t *StarTempl) TableName() string {
	return "user_starTempl"
}
func CreateStarTemplToUser(o orm.Ormer, starTeml StarTempl) (StarTempl, error) {
	o.Begin()
	templ, e := IncreaseTemplStar(o, starTeml.Templ.Uuid)
	starTeml.Templ = &templ
	_, err := o.Insert(&starTeml)
	if err != nil {
		o.Rollback()
		return StarTempl{}, fmt.Errorf("Create starTemp is failed, %s", err)
	} else if e != nil {
		o.Rollback()
		return StarTempl{}, fmt.Errorf("Create starTemp is failed, %s", e)
	} else {
		o.Commit()
	}

	return starTeml, err
}

func DeleteStarTemplToUser(o orm.Ormer, s StarTempl) error {
	o.Begin()
	_, e := decreaseTemplStar(o, s.Templ.Uuid)
	_, err := o.Delete(&s)
	if err != nil || e != nil {
		fmt.Errorf("delete starTemp is failed, %s,%s", err, e)
		o.Rollback()
	} else {
		o.Commit()
	}
	return err
}

func DeleteStarTempl(o orm.Ormer, starTemplId string) error {
	templ := []StarTempl{}
	_, err := o.QueryTable(StarTempl{}).Filter("templ_id", starTemplId).All(&templ)
	if err != nil {
		fmt.Errorf("get starTemplList failed,%s", err)
	}
	o.Begin()
	for k, v := range templ {
		_, err := o.Delete(&v)
		if err != nil {
			fmt.Errorf("delete starTempl %s is failed,%s", templ[k].Uuid, err)
			o.Rollback()
			return err
		}
	}
	o.Commit()
	return err
}
func GetStarTemplByUserIdAndTemplId(o orm.Ormer, userId string, templId string) (StarTempl, error) {
	templ := StarTempl{}
	err := o.QueryTable(StarTempl{}).Filter("templ_id", templId).Filter("user_id", userId).One(&templ)
	return templ, err
}
func ListStarTemplAll(o orm.Ormer, userID []string, query *dataselect.DataSelectQuery) ([]StarTempl, int64, error) {
	allTempl := []StarTempl{}
	origin := o.QueryTable(StarTempl{})
	origin, count, err := util.Search(origin, userID, query, existKeyInStarTempl)
	origin.All(&allTempl)
	for k, v := range allTempl {
		o.LoadRelated(&v, "templ")
		allTempl[k] = v
	}
	return allTempl, count, err
}
